<template>
  <div id="approveconfirmcomp">
    <!-- Form-开始 -->
    <el-dialog title="更改审核医生" width="500px" v-model="dialogFormVisible" draggable>
      <vxe-form
        ref="pagepanelnameForm"
        :data="form"
        :title-width="formLabelWidth"
        className="margin-bottom-sm"
      >
        <vxe-form-item field="name" title="用户名称" span="24">
          <SelectDataList
            ref="employeeSelectRef"
            :url="'/api/sys/hisEmployee/getEmployeePageList'"
            :displayField="[
              { title: '编号', props: 'code' }, //列标题
              { title: '名称', props: 'name' }
            ]"
            :inputKeyName="'seachValue'"
            :isPage="true"
            :placeholder="'点击选择员工'"
            @selectDataRow="SelectRowClick"
            v-model="form.name"
          />
        </vxe-form-item>
        <vxe-form-item field="name" title="授权码" span="24">
          <vxe-input
            ref="pswInput"
            v-model="form.password"
            autocomplete="new-password"
            name="password"
            type="password"
            auto-complete="new-password"
            clearable
          />
        </vxe-form-item>
      </vxe-form>
      <div v-if="origin !== 2">
        <div class="line-bottom solid-top margin-bottom-sm"></div>
        <vxe-radio-group v-model="radioEditType" class="margin-top cu-list" style="width: 100%">
          <div class="cu-item readio-item">
            <vxe-radio :label="1" content="修改当前标本"></vxe-radio>
            <br />
          </div>
          <div class="cu-item readio-item">
            <vxe-radio :label="2" content="修改所有未审核标本"></vxe-radio>
            <br />
          </div>
          <div class="cu-item readio-item flex justify-between">
            <div class="" style="vertical-align: middle; width: 160px">
              <vxe-radio :label="3" content="指定标本号修改"></vxe-radio>
            </div>
            <vxe-input
              class="margin-left-sm"
              v-model="inputCodeRange"
              placeholder="eg:1-4,6,7-15"
              :disabled="radioEditType !== 3"
            ></vxe-input>
          </div>
        </vxe-radio-group>
        <div
          class="line-bottom solid-top padding-top-sm padding-bottom-sm margin-top-sm margin-bottom-sm"
        >
          <vxe-checkbox v-model="rememberDateTime" content="记忆授权时间"></vxe-checkbox>
        </div>

        <div>
          <vxe-radio-group
            v-model="radio"
            style="width: 100%"
            :disabled="!rememberDateTime"
            @change="radioChange"
          >
            <el-row>
              <el-col :span="6"
                ><vxe-radio-button
                  :label="'24'"
                  border
                  content="24小时"
                  style="width: 100%"
                ></vxe-radio-button
              ></el-col>
              <el-col :span="6"
                ><vxe-radio-button
                  :label="'12'"
                  border
                  content="12小时"
                  style="width: 100%"
                ></vxe-radio-button
              ></el-col>
              <el-col :span="6"
                ><vxe-radio-button
                  :label="'5'"
                  border
                  content="5小时"
                  style="width: 100%"
                ></vxe-radio-button
              ></el-col>
              <el-col :span="6"
                ><vxe-radio-button
                  :label="'Today'"
                  border
                  content="当天"
                  style="width: 100%"
                ></vxe-radio-button
              ></el-col>
            </el-row>
            <div></div>
            <vxe-toolbar class-name="margin-top-sm">
              <template #buttons>
                <vxe-radio-button :label="'Self'" border content="自定义"></vxe-radio-button>
                <vxe-input
                  :disabled="radio !== 'Self'"
                  v-model="num"
                  placeholder="可输入小数"
                  type="float"
                  :step="1"
                  min="0.01"
                  max="23.59"
                  @change="numChange"
                ></vxe-input>
                <el-tag type="danger" style="margin-left: 0.5em">小时</el-tag>
              </template>
            </vxe-toolbar>
          </vxe-radio-group>
          <el-row style="padding-top: 20px">
            <el-col :span="4">当前时间：</el-col>
            <el-col :span="20">{{ timeData.currentTime }}</el-col>
          </el-row>
          <el-row style="padding-top: 10px">
            <el-col :span="4">结束时间：</el-col>
            <el-col :span="20">{{ timeData.expressIn }}</el-col>
          </el-row>
        </div>
      </div>

      <div class="flex justify-end">
        <el-button type="primary" v-loading="showLoading" @click="cacheEmployeeInfo()"
          >保存</el-button
        >
        <el-button @click="closeDialog()"> 取消</el-button>
      </div>
    </el-dialog>
    <!-- Form-结束 -->
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, watch, onMounted } from 'vue';
import { pageSizes, DateToString, formatDateTime, IsEmpty } from '../../../utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { VXETable } from 'vxe-table';
import XEUtils from 'xe-utils';
import { AppStore } from '../../../stores/store';
import axios from 'axios';
import SelectDataList from '@/components/SelectDataList.vue';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let showLoading = ref(false);

let dialogFormVisible = ref(false);//默认是关闭状态

let props = defineProps({
  isLocall: String, //是否存储到本地
  IsShow: Boolean,
  origin: Number //来源，弹框在哪个地方打开的。1:快捷菜单,2:批次审核
  //modelValue: String, //输入框绑定参数
  // inputKeyName: String, //查询入参名称
  // placeholder: { type: String, default: '点击选择' } //弹框标题
}) as any;

defineExpose({
  initPage
})

// 接收父组件传过来的弹框展开状态
function initPage(row:any){
  dialogFormVisible.value = row
}

let origin = ref(props.origin);
//   //#region  变量
let KeyObj = { wtId: '', scheduleDate: '' };
let IsCallBackApprove = false;

let form = reactive({ seachValue: '', id: '', name: '', code: '', password: '' });
let loading = ref(false);
// let pageSizeList = PageSizeList;
// let pageSize = PageSizeList[0];
let formLabelWidth = '100px';
let radioEditType = ref(2);
let radio = ref('Today');
let rememberDateTime = ref(true);
let inputCodeRange = ref('');
let num = ref(1.0);
let timeData = reactive({
  currentTime: DateToString(new Date()),
  expressIn: formatDateTime(new Date().valueOf(), 'yyyy-MM-dd 23:59:59')
});

let formTitle = ref('');

//   //#region  Methods
//   function created() {
//     //ToDo
//   }
//   function mounted() {
//     //ToDo
//     setTimeout(() => {
//       form.id = '';
//       form.code = '';
//       form.password = '';
//     }, 1000);
//   }
//点击保存校验编号与授权码
// async function cacheEmployeeInfo() {
//   if (IsEmpty(form.name) || IsEmpty(form.code)) {
//     VxeMessage('请选择医师！', VxeNotifyType.error);
//     return;
//   }
//   if (IsEmpty(form.password)) {
//     VxeMessage('请输入授权码!', VxeNotifyType.error);
//     return;
//   }
//   const data = { params: { code: form.code, empowerNum: form.password } }
//   proxy.$http
//     .get('/api/sys/hisEmployee/getEmployeeByCodeAndNum', data)
//     .then((res: any) => {
//       if (res.status.code === 200) {
//         VxeMessage('授权成功', VxeNotifyType.success);
//         dialogFormVisible.value = false;

//       } else {
//         VxeMessage(res.status.msg, VxeNotifyType.error);
//         return;
//       }
//     })
//     .catch((err: any) => {
//       VxeMessage('授权异常', VxeNotifyType.error);
//     });

// }

// 点击组件表格行
function SelectRowClick(row) {
  form.name = row.name;
  form.code = row.code;
}

// 取消操作
function closeDialog() {
  // $emit('dialogVisible', dialogFormVisible);
  IsCallBackApprove = false;
  formTitle.value = '审核';
  dialogFormVisible.value = false;
  form = {
    seachValue: '',
    id: '',
    name: '',
    code: '',
    password: ''
  };
  radioEditType.value = 2;
  radio.value = 'Today';
  //$emit('dialogVisible', dialogFormVisible);
  proxy.$emit('closeSHowApproveConfirm');
}

async function cacheEmployeeInfo() {
  if (IsEmpty(form.name) || IsEmpty(form.code)) {
    VxeMessage('请选择医师！', VxeNotifyType.error);
    return;
  }
  if (IsEmpty(form.password)) {
    VxeMessage('请输入授权码!', VxeNotifyType.error);
    return;
  }
  const data = { params: { code: form.code, empowerNum: form.password } };
  loading.value = true;
  const res = await new Promise((resolve, reject) => {
    proxy.$http
      .get('/api/sys/hisEmployee/getEmployeeByCodeAndNum', data)
      .then((res: any) => {
        if (res.status.code === 200) {
          VxeMessage('授权成功', VxeNotifyType.success);
          dialogFormVisible.value = false;
          if (origin.value === 2) {
            proxy.$emit('Confirm', {
              reviewerId: form.id,
              name: form.name,
              code: form.code,
              type: 'reviewer'
            });
            loading.value = false;
            return;
          }
          resolve(true);
        } else {
          const second = new Date(timeData.expressIn).getTime() - new Date().getTime(); //距清除审核人剩余的时间（毫秒）
          const time = setTimeout(() => {
            clearTimeout(time);
            sessionStorage.removeItem('locChkDoctor');
          }, second);
          resolve(false);
          VxeMessage(res.status.msg, VxeNotifyType.error);
          return;
        }
      })
      .catch((err: any) => {
        VxeMessage('授权异常', VxeNotifyType.error);
        resolve(false);
      });
  });

  if (res) {
    //#endregion 【验证通过，把数据保存在会话存储中】
    if (props.isLocall) {
      //localStorage
      if (formTitle.value === '审核' && rememberDateTime) {
        sessionStorage.setItem(
          'locChkDoctor',
          JSON.stringify({
            reviewerId: form.id,
            code: form.code,
            name: form.name,
            expressin: new Date(formatDateTime(timeData.expressIn, 'yyyy-MM-dd hh:mm:ss')).valueOf()
          })
        );
        if (IsCallBackApprove) {
          proxy.$emit('Confirm', {
            reviewerId: form.id,
            name: form.name,
            code: form.code,
            type: 'reviewer'
          });
        }
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwerId',
          value: form.id
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwer',
          value: form.name
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwerCode',
          value: form.code
        });
      }
      if (formTitle.value === '检验' && rememberDateTime) {
        sessionStorage.setItem(
          'locChkDoctorReger',
          JSON.stringify({
            targetUserId: form.id,
            code: form.code,
            name: form.name,
            expressin: new Date(formatDateTime(timeData.expressIn, 'yyyy-MM-dd hh:mm:ss')).valueOf()
          })
        );
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwerId',
          value: form.name
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'reger',
          value: form.name
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'regerCode',
          value: form.code
        });
      }
    } else {
      //localStorage
      if (formTitle.value == '审核' && rememberDateTime) {
        sessionStorage.setItem(
          'ApproveConfirm',
          JSON.stringify({
            reviewerId: form.id,
            code: form.code,
            name: form.name,
            expressin: new Date(formatDateTime(timeData.expressIn, 'yyyy-MM-dd hh:mm:ss')).valueOf()
          })
        );
        if (IsCallBackApprove) {
          proxy.$emit('Confirm', {});
        }
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwerId',
          value: form.id
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwer',
          value: form.id
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwerCode',
          value: form.id
        });
      }
      if (formTitle.value == '检验' && rememberDateTime) {
        sessionStorage.setItem(
          'ApproveConfirmReger',
          JSON.stringify({
            targetUserId: form.id,
            code: form.code,
            name: form.name,
            expressin: new Date(formatDateTime(timeData.expressIn, 'yyyy-MM-dd hh:mm:ss')).valueOf()
          })
        );
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwerId',
          value: form.id
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwer',
          value: form.id
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwerCode',
          value: form.id
        });
      }
    }
    // #endregion

    //#region 更新选项
    if (radioEditType.value === 1) {
      //todo
      proxy.l$emit('uptCallBack', {
        type: 1,
        wl: [],
        status: true,
        targetUserId: form.id,
        targetUserCode: form.code,
        targetUserName: form.name
      });
    }
    // if (radioEditType === 2 || radioEditType === 3) {
    let url = '/api/lims/work-lists-views/update-reviewers-many';
    if (formTitle.value === '检验') {
      url = '/api/lims/work-lists-views/update-registranters-many';
    }
    let data = {
      wtId: IsEmpty(KeyObj.wtId) ? null : KeyObj.wtId,
      scheduleDate: KeyObj.scheduleDate,
      targetUserId: form.id,
      codeRange: ''
    };
    if (radioEditType.value === 1) {
      data.codeRange = sessionStorage.getItem('CurCodeAppConfirmComp');
    }
    if (radioEditType.value === 3) {
      if (IsEmpty(inputCodeRange)) {
        VxeMessage('请填写要修改的标本号', VxeNotifyType.error);
        // (this as any).$XModal.message({ content: '请填写要修改的标本号!', status: 'warning' });
        return;
      }
      data.codeRange = inputCodeRange;
    }
    const result: any = await new Promise((resolve, reject) => {
      axios
        .post(url, data)
        .then((result1: any) => {
          resolve(result1);
        })
        .catch((resultErr) => {
          if (
            resultErr.data.error.message.indexOf(
              'The database operation was expected to affect 1 row(s)'
            ) > -1
          ) {
            //todo
            resolve(null);
            return;
          }
          VxeMessage('更新标本错误', VxeNotifyType.error);
          //(this as any).$XModal.message({ content: '更新标本错误!', status: 'warning' });
          resolve(resultErr);
        });
    });
    if (result) {
      proxy.$emit('uptCallBack', {
        type: radioEditType.value,
        wl: result.items,
        status: true,
        targetUserId: form.id,
        targetUserCode: form.code,
        targetUserName: form.name
      });
    }
    // }
    //#endregion
    if (origin.value === 1) {
      const wl = ref([]);
      result.items.forEach((item) => {
        wl.value.push(item.id);
      });
      //localStorage
      if (formTitle.value === '审核' && rememberDateTime.value) {
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwerType',
          value: radioEditType
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'revwerWL',
          value: wl
        });
      }
      if (formTitle.value === '检验' && rememberDateTime.value) {
        proxy.$store.commit('setTestDoctorObj', {
          key: 'regerType',
          value: radioEditType.value
        });
        proxy.$store.commit('setTestDoctorObj', {
          key: 'regerWL',
          value: radioEditType.value
        });
      }
    }

    //#region  清空内容
    IsCallBackApprove = false;
    formTitle.value = '审核';
    dialogFormVisible.value = false;
    form = {
      seachValue: '',
      id: '',
      name: '',
      code: '',
      password: ''
    };
    radioEditType.value = 2;
    radio.value = 'Today';
    //#endregion
    dialogFormVisible.value = false;
    proxy.$emit('dialogVisible', dialogFormVisible);
  }
  loading.value = false;
}

//单选改变
function radioChange(e) {
  try {
    const numObj = 1;
    switch (e.label) {
      case '24':
        timeData.expressIn = DateToString(new Date().valueOf() + 24 * 60 * 60 * 1000);
        break;
      case '12':
        timeData.expressIn = DateToString(new Date().valueOf() + 12 * 60 * 60 * 1000);
        break;
      case '5':
        timeData.expressIn = DateToString(new Date().valueOf() + 5 * 60 * 60 * 1000);
        break;
      case 'Today':
        timeData.expressIn = formatDateTime(new Date().valueOf(), 'yyyy-MM-dd 23:59:59');
        break;
      case 'Self':
        timeData.expressIn = DateToString(new Date().valueOf() + num.value * 60 * 60 * 1000);
        break;
      default:
        break;
    }
  } catch (error) {
    //todo
  }
}
//自定义数值改变
function numChange(e) {
  timeData.expressIn = DateToString(new Date().valueOf() + num.value * 60 * 60 * 1000);
}
</script>
<style lang="scss" scope>
#pagepanelname {
  .tool {
    margin: 10px 15px;

    .el-row {
      .tool-left,
      .tool-right {
        background-color: bg-white;
      }

      .el-form-item {
        margin-top: 10px;
        margin-bottom: 10px;
      }
    }
  }

  .el-divider--vertical {
    height: 20px;
  }
}

.readio-item {
  height: 28px;
  line-height: 28px;
  vertical-align: middle;
}

.readio-item > label {
  margin-top: calc((28px - 16px) / 2);
}

.readio-item > div > label {
  margin-top: calc((28px - 16px) / 2);
}
</style>
